<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * Audit trail table
 */
class Audit_model extends MY_Model
{
    const ADD=1;
    const EDIT=2;
    const UPDATE=3;
    const DELETE=4;
    const LOGIN=5;
    const LOGOUT=6;
    const UPLOAD=7;
    const PROCESS=8;
    const UNLOCK=9; // Unlock user
    
    private $start=null, $end=null;
    private $by_user=0;
    
    public function __construct() {
        parent::__construct();
        $this->load->library('session');
    }
    
    public function setStart($start){
        $this->start=$start;
        return $this;
    }
    public function setEnd($end){
        $this->end=$end;
        return $this;
    }
    public function setRange($start, $end){
        $this->start=$start;
        $this->end=$end;
        return $this;
    }
    public function setuser($userId){
        $this->by_user=$userId;
        return $this;
    }
    
    /**
     * 
     * @param type $event
     * @param array|str $param 
     *   user => user id
     *   msg => Message/comment
     * @return boolean
     * @throws Exception
     */
    public function save($event, $param = array()){
        log_message('info',__METHOD__.' -> UserId');
        $retparam='';
        ob_start();
        print_r($param, TRUE);
        $retparam = ob_get_contents();
        ob_end_clean();
        
        log_message('info','UserId'.  $retparam);
        
        $data=array(
            'user_id' => (is_array($param))?$param['user']:$this->session->userdata('user_id'),
            'event' => $event,
            'date'=>date('Y-m-d'),
            'time'=>date('H:i:s'),
            'timestamp'=>time(),
            'ip'=>$this->get_ip(),
        );
        log_message('error','UserId: '.$data['user_id']);
        $data['comment'] = ((is_array($param) && isset($param['account_name']))?$param['account_name']:$this->session->userdata('account_name')).' --> '
                . (is_array($param)?$param['msg']:$param);
        if (!$data['user_id']){
            log_message('error','UserId not exist, get the session data then');
            $data['user_id'] = $this->session->userdata('user_id');
        }
        try{
            return $this->insert($data);
        }  catch (Exception $e){
            log_message('error','Exception: Saving Audit trails failed');
            throw new Exception('Saving Audit trails failed');
        }
        return false;
    }
    
    public function get_audit($page=1, $limit=30)
    {
        $this->db->join('users u', 'audits.user_id = u.id');
        //$this->db->join( 'roles r', 'r.id = ur.roles_id' );
        if ($this->start && $this->end){
            $this->db->where('timestamp >=', $this->start);
            $this->db->where('timestamp <=', $this->end);
        }
        if ($this->by_user){
            $this->db->where('user_id', $this->by_user);
        }
        $this->db->order_by('audits.timestamp', 'DESC');
        return $this->db->get($this->_table)->result();
        //return $this->get($this->_table, $limit)->result();
        //return $this->get($this->_table, $page, $limit)->result();
        //return $this->get($this->_table)->{$this->_return_type()}();
        //return $this->get_by( array( 'r.name' => $role, 'ur.users_id' => $user ) );
    }
    
    private function get_ip()
    {
        return  (isset($_SERVER['HTTP_X_REAL_IP'])?$_SERVER['HTTP_X_REAL_IP']:(isset($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['SERVER_ADDR']));
    }
    
}